<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    
    <title>
        
        Darklovy</title>
    <meta name="description" content>
    <meta name="keywords" content>
    <meta name="HandheldFriendly" content="True">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <link rel="shortcut icon" href="/">
    <link rel="alternate" href="/atom.xml" title="Darklovy">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta property="og:type" content="website">
<meta property="og:title" content="Darklovy">
<meta property="og:url" content="https://www.ttxxly.top/index.html">
<meta property="og:site_name" content="Darklovy">
<meta property="og:locale" content="en">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Darklovy">

    <link href="https://fonts.googleapis.com/css?family=Inconsolata|Titillium+Web" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto+Mono" rel="stylesheet">
    <link href="//cdn.bootcss.com/node-waves/0.7.5/waves.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/style.css">
    <script>
        function setLoadingBarProgress(num) {
            document.getElementById('loading-bar').style.width = num + "%";
        }
    </script>
</head>
</html>
<body>
  <div id="loading-bar-wrapper">
  <div id="loading-bar"></div>
</div>


  <script>setLoadingBarProgress(20)</script> 
  <header class="l_header">
	<div class='wrapper'>
		<div class="nav-main container container--flex">
			<a class="logo flat-box" href='/' >
				Darklovy
			</a>
			<div class='menu'>
				<ul class='h-list'>
					
						<li>
							<a class='flat-box nav-Home' href='/'>
								首页
							</a>
						</li>
					
						<li>
							<a class='flat-box nav-archives' href='/archives'>
								归档
							</a>
						</li>
					
						<li>
							<a class='flat-box nav-categories' href='/categories'>
								分类
							</a>
						</li>
					
						<li>
							<a class='flat-box nav-tags' href='/tags'>
								标签
							</a>
						</li>
					
						<li>
							<a class='flat-box nav-algorithm' href='https://book.algorithm.ttxxly.top/'>
								算法
							</a>
						</li>
					
						<li>
							<a class='flat-box nav-python' href='https://book.python.ttxxly.top/'>
								python
							</a>
						</li>
					
						<li>
							<a class='flat-box nav-about' href='/about'>
								关于
							</a>
						</li>
					
				</ul>
				<div class='underline'></div>
			</div>
			
				<div class="m_search">
					<form name="searchform" class="form u-search-form">
						<input type="text" class="input u-search-input" placeholder="Search" />
						<span class="icon icon-search"></span>
					</form>
				</div>
			
			<ul class='switcher h-list'>
				
					<li class='s-search'><a href='javascript:void(0)'><span class="icon icon-search flat-box"></span></a></li>
				
				<li class='s-menu'><a href='javascript:void(0)'><span class="icon icon-menu flat-box"></span></a></li>
			</ul>
		</div>
		
		<div class='nav-sub container container--flex'>
			<a class="logo" class="flat-box" href='javascript:void(0)'>
				Word of Forks
			</a>

			<ul class='switcher h-list'>
				<li class='s-comment'><a href='javascript:void(0)'><span class="icon icon-chat_bubble_outline flat-box"></span></a></li>
				<li class='s-top'><a href='javascript:void(0)'><span class="icon icon-arrow_upward flat-box"></span></a></li>
				<li class='s-toc'><a href='javascript:void(0)'><span class="icon icon-format_list_numbered flat-box"></span></a></li>
			</ul>
		</div>
	</div>
</header>
<aside class="menu-phone">
	<nav>
		
			<a href="/" class="nav-Home nav">
				首页
			</a>
		
			<a href="/archives" class="nav-archives nav">
				归档
			</a>
		
			<a href="/categories" class="nav-categories nav">
				分类
			</a>
		
			<a href="/tags" class="nav-tags nav">
				标签
			</a>
		
			<a href="https://book.algorithm.ttxxly.top/" class="nav-algorithm nav">
				算法
			</a>
		
			<a href="https://book.python.ttxxly.top/" class="nav-python nav">
				python
			</a>
		
			<a href="/about" class="nav-about nav">
				关于
			</a>
		
	</nav>
</aside>

    <script>setLoadingBarProgress(40);</script>
  <div class="l_body">
    <div class='container clearfix'>
      <div class='l_main'>
        
<section class="post-list">
	
    <div class='post-wrapper'>
      <article class="post reveal">
  <section class="meta">
    
    <h2 class="title">
      <a href="/2019/03/02/Java-ArrayList/">
        Java ArrayList
      </a>
    </h2>
    
    <time>
      Mar 2, 2019
    </time>
		
  </section>
  <section class="article typo">
	  <p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html" target="_blank" rel="noopener">Java 8 官方文档链接</a></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">java.lang.Object</span><br><span class="line">	java.util.AbstractCollection&lt;E&gt;</span><br><span class="line">		java.util.AbstractList&lt;E&gt;</span><br><span class="line">			java.util.ArrayList&lt;E&gt;</span><br><span class="line">All Implemented Interfaces:</span><br><span class="line">	Serializable, Cloneable, Iterable&lt;E&gt;, Collection&lt;E&gt;, List&lt;E&gt;, RandomAccess</span><br><span class="line">Direct Known Subclasses:</span><br><span class="line">	AttributeList, RoleList, RoleUnresolvedList</span><br></pre></td></tr></table></figure>
<p>[TOC]</p>
<h3 id="ArrayList-简介"><a href="#ArrayList-简介" class="headerlink" title="ArrayList 简介"></a>ArrayList 简介</h3><ul>
<li><code>ArrayList</code> 是基于数组实现的，是一个动态数组，其容量能自动增长。</li>
<li><code>ArrayList</code> 不是线程安全的。多线程环境下请考虑用一下两种方案：<ul>
<li><code>Collections.synchronizedList(List list)</code> 函数返回一个线程安全的ArrayList类</li>
<li>concurrent并发包下的 <code>CopyOnWriteArrayList</code> 类</li>
<li><code>Vector</code> 类 不建议使用。</li>
</ul>
</li>
<li><code>ArrayList</code> 实现了 <code>Serializable</code> 接口，因此支持序列化，能够通过序列化传输。</li>
<li><code>ArrayList</code> 实现了 <code>Cloneable</code> 接口，即覆盖了函数clone()，能被克隆。</li>
<li><code>ArrayList</code> 实现了 <code>RandmoAccess</code>接口，即提供了随机访问功能。<br>  RandmoAccess是java中用来被List实现，为List提供快速访问功能的。<br>  在ArrayList中，我们即可以通过元素的序号快速获取元素对象.</li>
</ul>
<h3 id="ArrayList-源码剖析"><a href="#ArrayList-源码剖析" class="headerlink" title="ArrayList 源码剖析"></a>ArrayList 源码剖析</h3><p>源码分析基于 JDK 1.8.0_201 版本。</p>
<p><a href="https://paste.ubuntu.com/p/DNqhNPpvr4/" target="_blank" rel="noopener">https://paste.ubuntu.com/p/DNqhNPpvr4/</a></p>
<h4 id="字段总结"><a href="#字段总结" class="headerlink" title="字段总结"></a>字段总结</h4><p>从类 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/AbstractList.html" target="_blank" rel="noopener">java.util.AbstractList</a> 继承而来的字段</p>
<ul>
<li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/AbstractList.html#modCount" target="_blank" rel="noopener">modCount</a></li>
</ul>
<h4 id="构造器"><a href="#构造器" class="headerlink" title="构造器"></a>构造器</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">java.util.ArrayList&lt;E&gt;</span><br><span class="line"></span><br><span class="line">ArrayList()</span><br><span class="line">构造一个初始容量为<span class="number">10</span>的空列表。</span><br><span class="line"></span><br><span class="line">ArrayList(Collection&lt;? extends E&gt; c)</span><br><span class="line">按照集合的迭代器返回的顺序构造一个包含指定集合元素的列表。</span><br><span class="line">参数：</span><br><span class="line">c - 要将其元素放入此列表的集合</span><br><span class="line">抛出：</span><br><span class="line">NullPointerException - 如果指定的集合为<span class="keyword">null</span></span><br><span class="line"></span><br><span class="line">ArrayList(<span class="keyword">int</span> initialCapacity)</span><br><span class="line">构造具有指定初始容量的空列表。</span><br><span class="line">参数：</span><br><span class="line">initialCapacity - 列表的初始容量</span><br><span class="line">抛出：</span><br><span class="line">IllegalArgumentException - 如果指定的初始容量为负数</span><br></pre></td></tr></table></figure>
<h4 id="方法摘要"><a href="#方法摘要" class="headerlink" title="方法摘要"></a>方法摘要</h4><table>
<thead>
<tr>
<th>修饰符和类型</th>
<th>方法和描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>boolean</code></td>
<td><code>add(E e)</code>将指定的元素追加到此列表的末尾。</td>
</tr>
<tr>
<td><code>void</code></td>
<td><code>add(int index, E element)</code>将指定元素插入此列表中的指定位置。</td>
</tr>
<tr>
<td><code>boolean</code></td>
<td><code>addAll(Collection&lt;? extends E&gt; c)</code>将指定集合中的所有元素按指定集合的迭代器返回的顺序附加到此列表的末尾。</td>
</tr>
<tr>
<td><code>boolean</code></td>
<td><code>addAll(int index, Collection&lt;? extends E&gt; c)</code>从指定位置开始，将指定集合中的所有元素插入此列表。</td>
</tr>
<tr>
<td><code>void</code></td>
<td><code>clear()</code>从此列表中删除所有元素。</td>
</tr>
<tr>
<td><code>Object</code></td>
<td><code>clone()</code>返回此<code>ArrayList</code>实例的浅表副本。</td>
</tr>
<tr>
<td><code>boolean</code></td>
<td><code>contains(Object o)</code>如果此列表包含指定的元素，则返回<code>true</code>。</td>
</tr>
<tr>
<td><code>void</code></td>
<td><code>ensureCapacity(int minCapacity)</code>如有必要，增加此<code>ArrayList</code>实例的容量，以确保它至少可以容纳由minimum capacity参数指定的元素数。</td>
</tr>
<tr>
<td><code>void</code></td>
<td><code>forEach(Consumer&lt;? super E&gt; action)</code>对每个元素执行给定操作，<code>Iterable</code> 直到处理完所有元素或操作引发异常。</td>
</tr>
<tr>
<td><code>E</code></td>
<td><code>get(int index)</code>返回此列表中指定位置的元素。</td>
</tr>
<tr>
<td><code>int</code></td>
<td><code>indexOf(Object o)</code>返回此列表中第一次出现的指定元素的索引，如果此列表不包含该元素，则返回-1。</td>
</tr>
<tr>
<td><code>boolean</code></td>
<td><code>isEmpty()</code>如果此列表不包含任何元素，则返回<code>true</code>。</td>
</tr>
<tr>
<td><code>Iterator&lt;E&gt;</code></td>
<td><code>iterator()</code>以适当的顺序返回此列表中元素的迭代器。</td>
</tr>
<tr>
<td><code>int</code></td>
<td><code>lastIndexOf(Object o)</code>返回此列表中指定元素最后一次出现的索引，如果此列表不包含该元素，则返回-1。</td>
</tr>
<tr>
<td><code>ListIterator&lt;E&gt;</code></td>
<td><code>listIterator()</code>返回此列表中元素的列表迭代器（按适当顺序）。</td>
</tr>
<tr>
<td><code>ListIterator&lt;E&gt;</code></td>
<td><code>listIterator(int index)</code>从列表中的指定位置开始，返回列表中元素的列表迭代器（按正确顺序）。</td>
</tr>
<tr>
<td><code>E</code></td>
<td><code>remove(int index)</code>删除此列表中指定位置的元素。</td>
</tr>
<tr>
<td><code>boolean</code></td>
<td><code>remove(Object o)</code>从此列表中删除指定元素的第一个匹配项（如果存在）。</td>
</tr>
<tr>
<td><code>boolean</code></td>
<td><code>removeAll(Collection&lt;?&gt; c)</code>从此列表中删除指定集合中包含的所有元素。</td>
</tr>
<tr>
<td><code>boolean</code></td>
<td><code>removeIf(Predicate&lt;? super E&gt; filter)</code>删除此集合中满足给定谓词的所有元素。</td>
</tr>
<tr>
<td><code>protected void</code></td>
<td><code>removeRange(int fromIndex, int toIndex)</code>从此列表中删除索引介于其中<code>fromIndex</code>，包括和<code>toIndex</code>不包含的所有元素 。</td>
</tr>
<tr>
<td><code>void</code></td>
<td><code>replaceAll(UnaryOperator&lt;E&gt; operator)</code>将该列表的每个元素替换为将运算符应用于该元素的结果。</td>
</tr>
<tr>
<td><code>boolean</code></td>
<td><code>retainAll(Collection&lt;?&gt; c)</code>仅保留此列表中包含在指定集合中的元素。</td>
</tr>
<tr>
<td><code>E</code></td>
<td><code>set(int index, E element)</code>用指定的元素替换此列表中指定位置的元素。</td>
</tr>
<tr>
<td><code>int</code></td>
<td><code>size()</code>返回此列表中的元素数。</td>
</tr>
<tr>
<td><code>void</code></td>
<td><code>sort(Comparator&lt;? super E&gt; c)</code>根据指定的顺序对此列表进行排序 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html" target="_blank" rel="noopener"><code>Comparator</code></a>。</td>
</tr>
<tr>
<td><code>Spliterator&lt;E&gt;</code></td>
<td><code>spliterator()</code>在此列表中的元素上创建<em>后期绑定</em> 和<em>失败快速</em> <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html" target="_blank" rel="noopener"><code>Spliterator</code></a>。</td>
</tr>
<tr>
<td><code>List&lt;E&gt;</code></td>
<td><code>subList(int fromIndex, int toIndex)</code>返回指定的<code>fromIndex</code>，包含的和<code>toIndex</code>独占的列表部分的视图 。</td>
</tr>
<tr>
<td><code>Object[]</code></td>
<td><code>toArray()</code>以适当的顺序（从第一个元素到最后一个元素）返回包含此列表中所有元素的数组。</td>
</tr>
<tr>
<td><code>&lt;T&gt; T[]</code></td>
<td><code>toArray(T[] a)</code>以适当的顺序返回包含此列表中所有元素的数组（从第一个元素到最后一个元素）; 返回数组的运行时类型是指定数组的运行时类型。</td>
</tr>
<tr>
<td><code>void</code></td>
<td><code>trimToSize()</code>将此<code>ArrayList</code>实例的容量调整为列表的当前大小。</td>
</tr>
</tbody>
</table>
<h4 id="常用API"><a href="#常用API" class="headerlink" title="常用API"></a>常用API</h4><h4 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h4><h3 id="ArrayList遍历方式"><a href="#ArrayList遍历方式" class="headerlink" title="ArrayList遍历方式"></a>ArrayList遍历方式</h3><ol>
<li>通过<strong>迭代器遍历</strong>。即通过Iterator去遍历。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Integer value = <span class="keyword">null</span>;</span><br><span class="line">Iterator iter = list.iterator();</span><br><span class="line"><span class="keyword">while</span> (iter.hasNext()) &#123;</span><br><span class="line">    value = (Integer)iter.next();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="2">
<li><strong>随机访问，通过索引值去遍历</strong><br>由于ArrayList实现了RandomAccess接口，它支持通过索引值去随机访问元素。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Integer value = <span class="keyword">null</span>;</span><br><span class="line"><span class="keyword">int</span> size = list.size();</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;size; i++) &#123;</span><br><span class="line">    value = (Integer)list.get(i);        </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="3">
<li><strong>for循环遍历</strong><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Integer value = <span class="keyword">null</span>;</span><br><span class="line"><span class="keyword">for</span> (Integer integ:list) &#123;</span><br><span class="line">    value = integ;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="ArrayList-示例"><a href="#ArrayList-示例" class="headerlink" title="ArrayList 示例"></a>ArrayList 示例</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ArrayListTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 创建ArrayList</span></span><br><span class="line">        ArrayList list = <span class="keyword">new</span> ArrayList();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 将“”</span></span><br><span class="line">        list.add(<span class="string">"1"</span>);</span><br><span class="line">        list.add(<span class="string">"2"</span>);</span><br><span class="line">        list.add(<span class="string">"3"</span>);</span><br><span class="line">        list.add(<span class="string">"4"</span>);</span><br><span class="line">        <span class="comment">// 将下面的元素添加到第1个位置</span></span><br><span class="line">        list.add(<span class="number">0</span>, <span class="string">"5"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取第1个元素</span></span><br><span class="line">        System.out.println(<span class="string">"the first element is: "</span>+ list.get(<span class="number">0</span>));</span><br><span class="line">        <span class="comment">// 删除“3”</span></span><br><span class="line">        list.remove(<span class="string">"3"</span>);</span><br><span class="line">        <span class="comment">// 获取ArrayList的大小</span></span><br><span class="line">        System.out.println(<span class="string">"Arraylist size=: "</span>+ list.size());</span><br><span class="line">        <span class="comment">// 判断list中是否包含"3"</span></span><br><span class="line">        System.out.println(<span class="string">"ArrayList contains 3 is: "</span>+ list.contains(<span class="number">3</span>));</span><br><span class="line">        <span class="comment">// 设置第2个元素为10</span></span><br><span class="line">        list.set(<span class="number">1</span>, <span class="string">"10"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 通过Iterator遍历ArrayList</span></span><br><span class="line">        <span class="keyword">for</span>(Iterator iter = list.iterator(); iter.hasNext(); ) &#123;</span><br><span class="line">            System.out.println(<span class="string">"next is: "</span>+ iter.next());</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 将ArrayList转换为数组</span></span><br><span class="line">        String[] arr = (String[])list.toArray(<span class="keyword">new</span> String[<span class="number">0</span>]);</span><br><span class="line">        <span class="keyword">for</span> (String str:arr)</span><br><span class="line">            System.out.println(<span class="string">"str: "</span>+ str);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 清空ArrayList</span></span><br><span class="line">        list.clear();</span><br><span class="line">        <span class="comment">// 判断ArrayList是否为空</span></span><br><span class="line">        System.out.println(<span class="string">"ArrayList is empty: "</span>+ list.isEmpty());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    
    
    
	  <div class="full-width auto-padding tags">
      
        <a href="/tags/Java/">Java</a>
      
	  </div>
    
  </section>
</article>
    </div>
  
    <div class='post-wrapper'>
      <article class="post reveal">
  <section class="meta">
    
    <h2 class="title">
      <a href="/2019/03/01/Java-List-集合概述/">
        Java List 集合概述
      </a>
    </h2>
    
    <time>
      Mar 1, 2019
    </time>
		
  </section>
  <section class="article typo">
	  <p>List 集合包括 List 接口以及 List 接口的所有实现类。List 集合中的元素允许重复，各元素的顺序就是对象插入的顺序。类似 Java 数组，用户可通过使用索引（元素在集合中的位置）来访问集合中的元素。</p>
<h3 id="List-接口"><a href="#List-接口" class="headerlink" title="List 接口"></a>List 接口</h3><p>List 接口继承了 Collection 接口，因此包含了 Collection 中的所有方法。此外，List 接口还定义了两个非常重要的方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">get(<span class="keyword">int</span> index):获得指定索引位置的元素</span><br><span class="line">set(<span class="keyword">int</span> index, Object obj):将集合中指定索引位置的对象修改为指定的对象</span><br></pre></td></tr></table></figure>
<h3 id="List-接口的实现类"><a href="#List-接口的实现类" class="headerlink" title="List 接口的实现类"></a>List 接口的实现类</h3><p>List 接口的常用实现类有 ArrayList 与 LinkedList。</p>
<h4 id="ArrayList"><a href="#ArrayList" class="headerlink" title="ArrayList"></a>ArrayList</h4><p>ArrayList 类实现了可变的数组，允许保存所有元素，包括 null，并可以根据索引位置对集合进行快速的随机访问；缺点是向指定的索引位置插入对象或删除对象的速度较慢。</p>
<h4 id="LinkedList"><a href="#LinkedList" class="headerlink" title="LinkedList"></a>LinkedList</h4><p>LinkedList 类采用链表结构保存对象。这种结构的优点是便于向集合中插入和删除对象，需要向集合中插入、删除对象时，使用 LinkedList 类实现的 List 集合较高；但对于随机访问集合中的对象，使用 LinkedList 类实现 List 集合的效率较低。</p>
<p><strong>与数组相同，集合的索引也是从 0 开始的</strong></p>


    
    
    
	  <div class="full-width auto-padding tags">
      
        <a href="/tags/Java/">Java</a>
      
	  </div>
    
  </section>
</article>
    </div>
  
    <div class='post-wrapper'>
      <article class="post reveal">
  <section class="meta">
    
    <h2 class="title">
      <a href="/2019/02/28/Java-Collection-接口概述/">
        Java Collection 接口概述
      </a>
    </h2>
    
    <time>
      Feb 28, 2019
    </time>
		
  </section>
  <section class="article typo">
	  <p>Collection 接口是层次结构中的根接口。构成 Collection 的单位称为元素。 Collection 接口通常不能直接使用，但该接口提供了添加元素、删除元素、管理数据的方法。由于 List 接口与 Set 接口都继承了 Collection 接口，因此这个方法对 List 集合和 Set 集合都是通用的。</p>
<h3 id="Collection-接口常用方法"><a href="#Collection-接口常用方法" class="headerlink" title="Collection 接口常用方法"></a>Collection 接口常用方法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">add(E e)    将指定的对象添加到该集合中</span><br><span class="line">remove(Object o) 将指定的对象从该集合中移除</span><br><span class="line">isEmpty()       返回 <span class="keyword">boolean</span> 值，用于判断当前集合是否为空</span><br><span class="line">iterator()      返回在此 Collection 的元素上进行迭代的迭代器，用于遍历集合中的对象</span><br><span class="line">size()  <span class="comment">//返回 int 型值，获取该集合中的元素个数</span></span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Muster</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Collection&lt;String&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        list.add(<span class="string">"a"</span>);</span><br><span class="line">        list.add(<span class="string">"b"</span>);</span><br><span class="line">        list.add(<span class="string">"b"</span>);</span><br><span class="line">        Iterator&lt;String&gt; it = list.iterator();</span><br><span class="line">        <span class="keyword">while</span>(it.hasNext()) &#123;</span><br><span class="line">            String str = (String)it.next();</span><br><span class="line">            System.out.println(str);</span><br><span class="line">        &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>Iterator 的 next() 方法返回的是 Object</strong></p>


    
    
    
	  <div class="full-width auto-padding tags">
      
        <a href="/tags/Java/">Java</a>
      
	  </div>
    
  </section>
</article>
    </div>
  
    <div class='post-wrapper'>
      <article class="post reveal">
  <section class="meta">
    
    <h2 class="title">
      <a href="/2019/02/27/Java-集合类概述/">
        Java 集合类概述
      </a>
    </h2>
    
    <time>
      Feb 27, 2019
    </time>
		
  </section>
  <section class="article typo">
	  <p><code>java.util</code> 包中提供了一些集合类，这些集合类又被称为容器。<br>提到容器不难想到数组，集合类与数组的不同之处是，数组的长度是固定的，集合的长度是可变的；</p>
<p>数组用来存放基本类型的数据，集合用来存放对象的引用。<br>常用的集合有 List 集合、Set 集合和 Map 集合，其中 List 与 Set 继承了 Collection 接口，各接口还提供了不同的实现类。</p>
<h3 id="Java-集合的体系结构"><a href="#Java-集合的体系结构" class="headerlink" title="Java 集合的体系结构"></a>Java 集合的体系结构</h3><p>Java 集合中有两个重要的根接口：<code>Collection接口</code>和<code>Map接口</code>。<br><img src="/images/2019-2-27/1.png" alt></p>
<h4 id="Collection-接口"><a href="#Collection-接口" class="headerlink" title="Collection 接口"></a>Collection 接口</h4><p><code>Collection</code> 接口下有三个子接口：<code>set</code>、<code>List</code>、<code>Queue</code>接口。</p>
<ul>
<li><code>Set接口</code>：代表的是一个无序不可重复的集合，常用的实现类有:<code>HashSet</code>、<code>TreeSet</code>.</li>
<li><code>List接口</code>：代表的是有序可重复的集合，常用的实现类有：<code>ArrayList</code>、<code>Vector</code>.</li>
<li><code>Queue接口</code>：是 Java 提供的队列实现，是一种先进先出的数据结构。</li>
</ul>
<h4 id="Map-接口"><a href="#Map-接口" class="headerlink" title="Map 接口"></a>Map 接口</h4><p>Map 实现类主要用于保存具有映射关系（key-value）的数据。<br>常用的实现类有：<code>HashTable</code>、<code>HashMap</code>等。</p>


    
    
    
	  <div class="full-width auto-padding tags">
      
        <a href="/tags/Java/">Java</a>
      
	  </div>
    
  </section>
</article>
    </div>
  
    <div class='post-wrapper'>
      <article class="post reveal">
  <section class="meta">
    
    <h2 class="title">
      <a href="/2019/02/26/Java-常见异常/">
        Java 常见异常
      </a>
    </h2>
    
    <time>
      Feb 26, 2019
    </time>
		
  </section>
  <section class="article typo">
	  <p>在 Java 中提供了一些异常用来描述经常发生的错误，其中，有点需要程序员进行捕获处理或声明抛出，有的是由 java 虚拟机自动进行捕获处理的。</p>
<table>
<thead>
<tr>
<th>异常类</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>ClassCastException</td>
<td>类型转换异常</td>
</tr>
<tr>
<td>ClassNotFoundException</td>
<td>未找到相应类异常</td>
</tr>
<tr>
<td>ArithmeticException</td>
<td>算术异常</td>
</tr>
<tr>
<td>ArrayIndexOutOfBoundsException</td>
<td>数组下标越界异常</td>
</tr>
<tr>
<td>ArrayStoreException</td>
<td>数组中包含不兼容的值抛出的异常</td>
</tr>
<tr>
<td>SQLException</td>
<td>操作数据库异常类</td>
</tr>
<tr>
<td>NullPointerException</td>
<td>空指针异常</td>
</tr>
<tr>
<td>NoSuchFieldException</td>
<td>字段未找到异常</td>
</tr>
<tr>
<td>NoSuchMethodException</td>
<td>方法未找到异常</td>
</tr>
<tr>
<td>NumberFormatException</td>
<td>字符串转换为数字抛出的异常</td>
</tr>
<tr>
<td>NegativeArraySizeException</td>
<td>数组元素个数为负数抛出的异常</td>
</tr>
<tr>
<td>StringIndexOutOfBoundsException</td>
<td>字符串索引超出范围抛出的异常</td>
</tr>
<tr>
<td>IOException</td>
<td>输入输出异常</td>
</tr>
<tr>
<td>IllegalAccessException</td>
<td>不允许访问某类异常</td>
</tr>
<tr>
<td>InstantiationException</td>
<td>当应用程序试图使用 Class 类中的 newInstance() 方法常见一个类的实例，而指定的类对象无法被实例化时，抛出异常</td>
</tr>
<tr>
<td>EOFException</td>
<td>文件已结束异常</td>
</tr>
<tr>
<td>FileNotFoundException</td>
<td>文件未找到异常</td>
</tr>
</tbody>
</table>


    
    
    
	  <div class="full-width auto-padding tags">
      
        <a href="/tags/Java/">Java</a>
      
	  </div>
    
  </section>
</article>
    </div>
  
    <div class='post-wrapper'>
      <article class="post reveal">
  <section class="meta">
    
    <h2 class="title">
      <a href="/2019/02/25/Java-运行时异常/">
        Java 运行时异常
      </a>
    </h2>
    
    <time>
      Feb 25, 2019
    </time>
		
  </section>
  <section class="article typo">
	  <p>RunTimeException 异常是程序运行过程中产生的异常。Java类库的每个包中都定义了异常类，所有这些类都是 Throwable 类的子类。</p>
<p>Throwable 类派生了两个子类，分别是 Exception 和 Error 类。Error 类及其子类用来描述 Java 运行系统中的内部错误以及资源耗尽的错误，这类错误比较严重。Exception 类称为非致命性类，可以通过捕获处理使程序继续执行。Exception 类又根据错误发生的原因分为 RuntimeException 异常和除 RuntimeException 之外的异常。</p>
<h3 id="常见的-RuntimeException-异常"><a href="#常见的-RuntimeException-异常" class="headerlink" title="常见的 RuntimeException 异常"></a>常见的 RuntimeException 异常</h3><table>
<thead>
<tr>
<th>种类</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>NullPointerException</td>
<td>空指针异常</td>
</tr>
<tr>
<td>ArrayIndexOutOfBoundsException</td>
<td>数组下标越界异常</td>
</tr>
<tr>
<td>ArithmeticException</td>
<td>算术异常</td>
</tr>
<tr>
<td>ArrayStoreException</td>
<td>数组中包含不兼容的值抛出异常</td>
</tr>
<tr>
<td>IilegalArgumentException</td>
<td>非法参数异常</td>
</tr>
<tr>
<td>SecurityException</td>
<td>安全性异常</td>
</tr>
<tr>
<td>NegativeArraySizeException</td>
<td>数组长度为负异常</td>
</tr>
</tbody>
</table>


    
    
    
	  <div class="full-width auto-padding tags">
      
        <a href="/tags/Java/">Java</a>
      
	  </div>
    
  </section>
</article>
    </div>
  
    <div class='post-wrapper'>
      <article class="post reveal">
  <section class="meta">
    
    <h2 class="title">
      <a href="/2019/02/22/Java-枚举类型/">
        Java 枚举类型
      </a>
    </h2>
    
    <time>
      Feb 22, 2019
    </time>
		
  </section>
  <section class="article typo">
	  <p>使用枚举类型可以取代以往定义常量的方式，同时枚举类型还赋予程序在编译时进行检查的功能。</p>
<h3 id="使用枚举类型设置常量"><a href="#使用枚举类型设置常量" class="headerlink" title="使用枚举类型设置常量"></a>使用枚举类型设置常量</h3><p>以往设置常量，通常将常量放置在接口中，这样在程序中就可以直接使用，并且该常量不能被修改，因为在接口中定义常量时，该常量的修饰符为 final 与 static。</p>


    
    
    
	  <div class="full-width auto-padding tags">
      
        <a href="/tags/Java/">Java</a>
      
	  </div>
    
  </section>
</article>
    </div>
  
    <div class='post-wrapper'>
      <article class="post reveal">
  <section class="meta">
    
    <h2 class="title">
      <a href="/2019/02/21/Java-使用-Annotation-功能/">
        Java 使用 Annotation 功能
      </a>
    </h2>
    
    <time>
      Feb 21, 2019
    </time>
		
  </section>
  <section class="article typo">
	  <p>Java 中提供了 Annotation 功能，该功能可用于类、构造方法、成员变量、方法、参数等的声明中。该功能并不影响程序的运行，但是会对编译器警告灯辅助工具产生影响。</p>
<h3 id="定义-Annotation-类型"><a href="#定义-Annotation-类型" class="headerlink" title="定义 Annotation 类型"></a>定义 Annotation 类型</h3><p>在定义 Annotation 类型时，也需要用到用来定义接口的 interface 关键字，但需要在 interface 关键字前加一个 <code>@</code>符号，即定义 Annotation 类型的关键字为 <code>@interface</code>，这个关键字的隐含意思是继承了 <code>ava.lang.annotation.Annotation</code>接口.<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> NoMemberAnnotation &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>


    
    
    
	  <div class="full-width auto-padding tags">
      
        <a href="/tags/Java/">Java</a>
      
	  </div>
    
  </section>
</article>
    </div>
  
    <div class='post-wrapper'>
      <article class="post reveal">
  <section class="meta">
    
    <h2 class="title">
      <a href="/2019/02/20/Java-Class-类与-Java-反射/">
        Java Class 类与 Java 反射
      </a>
    </h2>
    
    <time>
      Feb 20, 2019
    </time>
		
  </section>
  <section class="article typo">
	  <p>通过 java 反射机制，可以在程序中访问已经装载到 JVM 中的 Java 对象的描述，实现访问、检测和修改描述 Java 对象本身信息的功能。 java 反射机制的功能十分强大，在 <code>java.lang.reflect</code> 包中提供了对该功能的支持。</p>
<p>从所周知，所有 Java 类均继承了 Object 类，在 Object 类中定义了一个 getClass() 方法，该方法返回一个类型为 Class 的对象。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Class textFieldC = textField.getClass();</span><br></pre></td></tr></table></figure></p>
<p>利用 Class 类的对象 textFieldC，可以访问用来返回该对象的 textField 对象的描述信息。</p>
<p>描述信息如下表所示：</p>
<table>
<thead>
<tr>
<th>组成部分</th>
<th>访问方法</th>
<th>返回值类型</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>包路径</td>
<td>getPackage()</td>
<td>Package 对象</td>
<td>获得该类的存放路径</td>
</tr>
<tr>
<td>类名称</td>
<td>getName()</td>
<td>String 对象</td>
<td>获得该类的名称</td>
</tr>
<tr>
<td>继承类</td>
<td>getSuperClass()</td>
<td>Class 对象</td>
<td>获得该类继承的类</td>
</tr>
<tr>
<td>实现接口</td>
<td>getInterfaces()</td>
<td>Class 型数组</td>
<td>获得该类实现的所有接口</td>
</tr>
<tr>
<td>构造方法</td>
<td>getConstructors()</td>
<td>Constructor 型数组</td>
<td>获得所有权限为 public 的构造方法</td>
</tr>
<tr>
<td>构造方法</td>
<td>getConstructor(Class&lt;?&gt;…parameterTypes)</td>
<td>Constructor 对象</td>
<td>获得权限为 public 的指定构造方法</td>
</tr>
<tr>
<td>构造方法</td>
<td>getDeclaredConstructors()</td>
<td>Constructors 型数组</td>
<td>获得所有构造方法，按声明顺序返回</td>
</tr>
<tr>
<td>构造方法</td>
<td>getDeclaredConstructor(Class&lt;?&gt;…parameterTypes)</td>
<td>Constructor 对象</td>
<td>获得指定构造方法</td>
</tr>
<tr>
<td>方法</td>
<td>getMethods()</td>
<td>Method 型数组</td>
<td>获得所有权限为 public 的方法</td>
</tr>
<tr>
<td>方法</td>
<td>getMethod(String name, Class&lt;?&gt;…parameterTypes)</td>
<td>Method 对象</td>
<td>获得权限为 public 的指定方法</td>
</tr>
<tr>
<td>方法</td>
<td>getDeclaredMethods()</td>
<td>Method 数组</td>
<td>获得所有方法，按声明顺序返回</td>
</tr>
<tr>
<td>方法</td>
<td>getDeclaredMethod(String name, Class&lt;?&gt;…parameterTypes)</td>
<td>Method 对象</td>
<td>获得指定方法</td>
</tr>
<tr>
<td>成员变量</td>
<td>getFields()</td>
<td>Field 型数组</td>
<td>获得所有权限为 public 的成员变量</td>
</tr>
<tr>
<td>成员变量</td>
<td>getField(String name)</td>
<td>Field 对象</td>
<td>获得权限为 public 的指定成员变量</td>
</tr>
<tr>
<td>成员变量</td>
<td>getDeclaredFields()</td>
<td>Field 型数组</td>
<td>获得所有成员变量，按声明顺序返回</td>
</tr>
<tr>
<td>成员变量</td>
<td>getDeclaredField(String name)</td>
<td>Field 对象</td>
<td>获得指定成员变量</td>
</tr>
<tr>
<td>内部类</td>
<td>getClasses()</td>
<td>Class 型数组</td>
<td>获得所有权限为public的内部类</td>
</tr>
<tr>
<td>内部类</td>
<td>getDeclaredClasses()</td>
<td>Class 型数组</td>
<td>获得所有内部类</td>
</tr>
<tr>
<td>内部类的声明类</td>
<td>getDeclaringClass()</td>
<td>Class 对象</td>
<td>如果该类为内部类，则返回它的成员类，否则返回 null</td>
</tr>
</tbody>
</table>


    
    
    
	  <div class="full-width auto-padding tags">
      
        <a href="/tags/Java/">Java</a>
      
	  </div>
    
  </section>
</article>
    </div>
  
    <div class='post-wrapper'>
      <article class="post reveal">
  <section class="meta">
    
    <h2 class="title">
      <a href="/2019/02/19/Java-日期与时间/">
        Java 日期与时间
      </a>
    </h2>
    
    <time>
      Feb 19, 2019
    </time>
		
  </section>
  <section class="article typo">
	  <p>java.util 包提供了 Date 类来封装当前的日期和时间。 Date 类提供两个构造函数来实例化 Date 对象。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">第一个构造函数使用当前日期和时间来初始化对象。</span><br><span class="line">Date( )</span><br><span class="line">    </span><br><span class="line">第二个构造函数接收一个参数，该参数是从<span class="number">1970</span>年<span class="number">1</span>月<span class="number">1</span>日起的毫秒数。</span><br><span class="line">Date(<span class="keyword">long</span> millisec)</span><br></pre></td></tr></table></figure>
<h3 id="常用方法"><a href="#常用方法" class="headerlink" title="常用方法"></a>常用方法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">boolean</span> <span class="title">after</span><span class="params">(Date date)</span></span></span><br><span class="line"><span class="function">若当调用此方法的Date对象在指定日期之后返回<span class="keyword">true</span>,否则返回<span class="keyword">false</span>。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">boolean</span> <span class="title">before</span><span class="params">(Date date)</span></span></span><br><span class="line"><span class="function">若当调用此方法的Date对象在指定日期之前返回<span class="keyword">true</span>,否则返回<span class="keyword">false</span>。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function">Object <span class="title">clone</span><span class="params">( )</span></span></span><br><span class="line"><span class="function">返回此对象的副本。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">compareTo</span><span class="params">(Date date)</span></span></span><br><span class="line"><span class="function">比较当调用此方法的Date对象和指定日期。两者相等时候返回0。</span></span><br><span class="line"><span class="function">调用对象在指定日期之前则返回负数。调用对象在指定日期之后则返回正数。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">compareTo</span><span class="params">(Object obj)</span></span></span><br><span class="line"><span class="function">若obj是Date类型则操作等同于<span class="title">compareTo</span><span class="params">(Date)</span> 。否则它抛出ClassCastException。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">boolean</span> <span class="title">equals</span><span class="params">(Object date)</span></span></span><br><span class="line"><span class="function">当调用此方法的Date对象和指定日期相等时候返回<span class="keyword">true</span>,否则返回<span class="keyword">false</span>。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">long</span> <span class="title">getTime</span><span class="params">( )</span></span></span><br><span class="line"><span class="function">返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">hashCode</span><span class="params">( )</span></span></span><br><span class="line"><span class="function">返回此对象的哈希码值。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">setTime</span><span class="params">(<span class="keyword">long</span> time)</span></span></span><br><span class="line"><span class="function">用自1970年1月1日00:00:00 GMT以后time毫秒数设置时间和日期。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function">String <span class="title">toString</span><span class="params">( )</span></span></span><br><span class="line"><span class="function">把此 Date 对象转换为以下形式的 String： dow mon dd hh:mm:ss zzz yyyy </span></span><br><span class="line"><span class="function">其中： dow 是一周中的某一天 <span class="params">(Sun, Mon, Tue, Wed, Thu, Fri, Sat)</span>。</span></span><br></pre></td></tr></table></figure>
<h3 id="获取当前日期时间"><a href="#获取当前日期时间" class="headerlink" title="获取当前日期时间"></a>获取当前日期时间</h3><p>Java中获取当前日期和时间很简单，使用 Date 对象的 toString() 方法来打印当前日期和时间，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line">  </span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DateDemo</span> </span>&#123;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">       <span class="comment">// 初始化 Date 对象</span></span><br><span class="line">       Date date = <span class="keyword">new</span> Date();</span><br><span class="line">        </span><br><span class="line">       <span class="comment">// 使用 toString() 函数显示日期时间</span></span><br><span class="line">       System.out.println(date.toString());</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">编译结果如下：</span><br><span class="line">Mon May <span class="number">04</span> <span class="number">09</span>:<span class="number">51</span>:<span class="number">52</span> CDT <span class="number">2013</span></span><br></pre></td></tr></table></figure>
<h3 id="日期比较"><a href="#日期比较" class="headerlink" title="日期比较"></a>日期比较</h3><p>Java使用以下三种方法来比较两个日期：</p>
<ul>
<li>使用 getTime() 方法获取两个日期（自1970年1月1日经历的毫秒数值），然后比较这两个值。</li>
<li>使用方法 before()，after() 和 equals()。例如，一个月的12号比18号早，则 new Date(99, 2, 12).before(new Date (99, 2, 18)) 返回true。</li>
<li>使用 compareTo() 方法，它是由 Comparable 接口定义的，Date 类实现了这个接口。</li>
</ul>
<h3 id="使用-SimpleDateFormat-格式化日期"><a href="#使用-SimpleDateFormat-格式化日期" class="headerlink" title="使用 SimpleDateFormat 格式化日期"></a>使用 SimpleDateFormat 格式化日期</h3><p>SimpleDateFormat 是一个以语言环境敏感的方式来格式化和分析日期的类。SimpleDateFormat 允许你选择任何用户自定义日期时间格式来运行。例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"><span class="keyword">import</span> java.text.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DateDemo</span> </span>&#123;</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">      Date dNow = <span class="keyword">new</span> Date( );</span><br><span class="line">      SimpleDateFormat ft = </span><br><span class="line">      <span class="keyword">new</span> SimpleDateFormat (<span class="string">"E yyyy.MM.dd 'at' hh:mm:ss a zzz"</span>);</span><br><span class="line"></span><br><span class="line">      System.out.println(<span class="string">"Current Date: "</span> + ft.format(dNow));</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">结果：</span><br><span class="line">Current Date: Wed <span class="number">2016.11</span>.09 at <span class="number">08</span>:<span class="number">23</span>:<span class="number">19</span> AM UTC</span><br></pre></td></tr></table></figure>
<h3 id="日期和时间的格式化编码"><a href="#日期和时间的格式化编码" class="headerlink" title="日期和时间的格式化编码"></a>日期和时间的格式化编码</h3><p>时间模式字符串用来指定时间格式。在此模式中，所有的 ASCII 字母被保留为模式字母，定义如下：</p>
<table>
<thead>
<tr>
<th><strong>字母</strong></th>
<th><strong>描述</strong></th>
<th><strong>示例</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>G</td>
<td>纪元标记</td>
<td>AD</td>
</tr>
<tr>
<td>y</td>
<td>四位年份</td>
<td>2001</td>
</tr>
<tr>
<td>M</td>
<td>月份</td>
<td>July or 07</td>
</tr>
<tr>
<td>d</td>
<td>一个月的日期</td>
<td>10</td>
</tr>
<tr>
<td>h</td>
<td>A.M./P.M. (1~12)格式小时</td>
<td>12</td>
</tr>
<tr>
<td>H</td>
<td>一天中的小时 (0~23)</td>
<td>22</td>
</tr>
<tr>
<td>m</td>
<td>分钟数</td>
<td>30</td>
</tr>
<tr>
<td>s</td>
<td>秒数</td>
<td>55</td>
</tr>
<tr>
<td>S</td>
<td>毫秒数</td>
<td>234</td>
</tr>
<tr>
<td>E</td>
<td>星期几</td>
<td>Tuesday</td>
</tr>
<tr>
<td>D</td>
<td>一年中的日子</td>
<td>360</td>
</tr>
<tr>
<td>F</td>
<td>一个月中第几周的周几</td>
<td>2 (second Wed. in July)</td>
</tr>
<tr>
<td>w</td>
<td>一年中第几周</td>
<td>40</td>
</tr>
<tr>
<td>W</td>
<td>一个月中第几周</td>
<td>1</td>
</tr>
<tr>
<td>a</td>
<td>A.M./P.M. 标记</td>
<td>PM</td>
</tr>
<tr>
<td>k</td>
<td>一天中的小时(1~24)</td>
<td>24</td>
</tr>
<tr>
<td>K</td>
<td>A.M./P.M. (0~11)格式小时</td>
<td>10</td>
</tr>
<tr>
<td>z</td>
<td>时区</td>
<td>Eastern Standard Time</td>
</tr>
<tr>
<td>‘</td>
<td>文字定界符</td>
<td>Delimiter</td>
</tr>
<tr>
<td>“</td>
<td>单引号</td>
<td>`</td>
</tr>
</tbody>
</table>
<h3 id="使用printf格式化日期"><a href="#使用printf格式化日期" class="headerlink" title="使用printf格式化日期"></a>使用printf格式化日期</h3><p>printf 方法可以很轻松地格式化时间和日期。使用两个字母格式，它以 %t 开头并且以下面表格中的一个字母结尾。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DateDemo</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">     <span class="comment">// 初始化 Date 对象</span></span><br><span class="line">     Date date = <span class="keyword">new</span> Date();</span><br><span class="line"> </span><br><span class="line">     <span class="comment">//c的使用  </span></span><br><span class="line">    System.out.printf(<span class="string">"全部日期和时间信息：%tc%n"</span>,date);          </span><br><span class="line">    <span class="comment">//f的使用  </span></span><br><span class="line">    System.out.printf(<span class="string">"年-月-日格式：%tF%n"</span>,date);  </span><br><span class="line">    <span class="comment">//d的使用  </span></span><br><span class="line">    System.out.printf(<span class="string">"月/日/年格式：%tD%n"</span>,date);  </span><br><span class="line">    <span class="comment">//r的使用  </span></span><br><span class="line">    System.out.printf(<span class="string">"HH:MM:SS PM格式（12时制）：%tr%n"</span>,date);  </span><br><span class="line">    <span class="comment">//t的使用  </span></span><br><span class="line">    System.out.printf(<span class="string">"HH:MM:SS格式（24时制）：%tT%n"</span>,date);  </span><br><span class="line">    <span class="comment">//R的使用  </span></span><br><span class="line">    System.out.printf(<span class="string">"HH:MM格式（24时制）：%tR"</span>,date);  </span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">结果：</span><br><span class="line"></span><br><span class="line">全部日期和时间信息：星期一 九月 <span class="number">10</span> <span class="number">10</span>:<span class="number">43</span>:<span class="number">36</span> CST <span class="number">2012</span>  </span><br><span class="line">年-月-日格式：<span class="number">2012</span>-<span class="number">09</span>-<span class="number">10</span>  </span><br><span class="line">月/日/年格式：<span class="number">09</span>/<span class="number">10</span>/<span class="number">12</span>  </span><br><span class="line">HH:MM:SS PM格式（<span class="number">12</span>时制）：<span class="number">10</span>:<span class="number">43</span>:<span class="number">36</span> 上午  </span><br><span class="line">HH:MM:SS格式（<span class="number">24</span>时制）：<span class="number">10</span>:<span class="number">43</span>:<span class="number">36</span>  </span><br><span class="line">HH:MM格式（<span class="number">24</span>时制）：<span class="number">10</span>:<span class="number">43</span></span><br></pre></td></tr></table></figure>
<h3 id="解析字符串为时间"><a href="#解析字符串为时间" class="headerlink" title="解析字符串为时间"></a>解析字符串为时间</h3><p>SimpleDateFormat 类有一些附加的方法，特别是parse()，它试图按照给定的SimpleDateFormat 对象的格式化存储来解析字符串。例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line"><span class="keyword">import</span> java.text.*;</span><br><span class="line">  </span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DateDemo</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">      SimpleDateFormat ft = <span class="keyword">new</span> SimpleDateFormat (<span class="string">"yyyy-MM-dd"</span>); </span><br><span class="line"> </span><br><span class="line">      String input = args.length == <span class="number">0</span> ? <span class="string">"1818-11-11"</span> : args[<span class="number">0</span>]; </span><br><span class="line"> </span><br><span class="line">      System.out.print(input + <span class="string">" Parses as "</span>); </span><br><span class="line"> </span><br><span class="line">      Date t; </span><br><span class="line"> </span><br><span class="line">      <span class="keyword">try</span> &#123; </span><br><span class="line">          t = ft.parse(input); </span><br><span class="line">          System.out.println(t); </span><br><span class="line">      &#125; <span class="keyword">catch</span> (ParseException e) &#123; </span><br><span class="line">          System.out.println(<span class="string">"Unparseable using "</span> + ft); </span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">result:</span><br><span class="line"></span><br><span class="line">$ java DateDemo</span><br><span class="line"><span class="number">1818</span>-<span class="number">11</span>-<span class="number">11</span> Parses as Wed Nov <span class="number">11</span> <span class="number">00</span>:<span class="number">00</span>:<span class="number">00</span> GMT <span class="number">1818</span></span><br><span class="line">$ java DateDemo <span class="number">2007</span>-<span class="number">12</span>-<span class="number">01</span></span><br><span class="line"><span class="number">2007</span>-<span class="number">12</span>-<span class="number">01</span> Parses as Sat Dec <span class="number">01</span> <span class="number">00</span>:<span class="number">00</span>:<span class="number">00</span> GMT <span class="number">2007</span></span><br></pre></td></tr></table></figure>
<h3 id="测量时间"><a href="#测量时间" class="headerlink" title="测量时间"></a>测量时间</h3><p>下面的一个例子表明如何测量时间间隔（以毫秒为单位）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line">  </span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DiffDemo</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">         <span class="keyword">long</span> start = System.currentTimeMillis( );</span><br><span class="line">         System.out.println(<span class="keyword">new</span> Date( ) + <span class="string">"\n"</span>);</span><br><span class="line">         Thread.sleep(<span class="number">5</span>*<span class="number">60</span>*<span class="number">10</span>);</span><br><span class="line">         System.out.println(<span class="keyword">new</span> Date( ) + <span class="string">"\n"</span>);</span><br><span class="line">         <span class="keyword">long</span> end = System.currentTimeMillis( );</span><br><span class="line">         <span class="keyword">long</span> diff = end - start;</span><br><span class="line">         System.out.println(<span class="string">"Difference is : "</span> + diff);</span><br><span class="line">      &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">         System.out.println(<span class="string">"Got an exception!"</span>);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">result:</span><br><span class="line"></span><br><span class="line">Fri Jan <span class="number">08</span> <span class="number">09</span>:<span class="number">48</span>:<span class="number">47</span> CST <span class="number">2016</span></span><br><span class="line"></span><br><span class="line">Fri Jan <span class="number">08</span> <span class="number">09</span>:<span class="number">48</span>:<span class="number">50</span> CST <span class="number">2016</span></span><br><span class="line"></span><br><span class="line">Difference is : <span class="number">3019</span></span><br></pre></td></tr></table></figure>
<h3 id="利用-Calendar-类在日期做加减"><a href="#利用-Calendar-类在日期做加减" class="headerlink" title="利用 Calendar 类在日期做加减"></a>利用 Calendar 类在日期做加减</h3><p>我们现在已经能够格式化并创建一个日期对象了，但是我们如何才能设置和获取日期数据的特定部分呢，比如说小时，日，或者分钟? 我们又如何在日期的这些部分加上或者减去值呢? 答案是使用Calendar 类。</p>
<p>Calendar类的功能要比Date类强大很多，而且在实现方式上也比Date类要复杂一些。</p>
<p>Calendar类是一个抽象类，在实际使用时实现特定的子类的对象，创建对象的过程对程序员来说是透明的，只需要使用getInstance方法创建即可。</p>
<h3 id="创建一个代表系统当前日期的Calendar对象"><a href="#创建一个代表系统当前日期的Calendar对象" class="headerlink" title="创建一个代表系统当前日期的Calendar对象"></a>创建一个代表系统当前日期的Calendar对象</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Calendar c = Calendar.getInstance();//默认是当前日期</span><br></pre></td></tr></table></figure>
<h4 id="创建一个指定日期的Calendar对象"><a href="#创建一个指定日期的Calendar对象" class="headerlink" title="创建一个指定日期的Calendar对象"></a>创建一个指定日期的Calendar对象</h4><p>使用Calendar类代表特定的时间，需要首先创建一个Calendar的对象，然后再设定该对象中的年月日参数来完成。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">//创建一个代表2009年6月12日的Calendar对象</span><br><span class="line">Calendar c1 = Calendar.getInstance();</span><br><span class="line">c1.set(2009, 6 - 1, 12);</span><br></pre></td></tr></table></figure>
<h4 id="Calendar类对象字段类型"><a href="#Calendar类对象字段类型" class="headerlink" title="Calendar类对象字段类型"></a>Calendar类对象字段类型</h4><p>Calendar类中用以下这些常量表示不同的意义，jdk内的很多类其实都是采用的这种思想</p>
<table>
<thead>
<tr>
<th>常量</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>Calendar.YEAR</td>
<td>年份</td>
</tr>
<tr>
<td>Calendar.MONTH</td>
<td>月份</td>
</tr>
<tr>
<td>Calendar.DATE</td>
<td>日期</td>
</tr>
<tr>
<td>Calendar.DAY_OF_MONTH</td>
<td>日期，和上面的字段意义完全相同</td>
</tr>
<tr>
<td>Calendar.HOUR</td>
<td>12小时制的小时</td>
</tr>
<tr>
<td>Calendar.HOUR_OF_DAY</td>
<td>24小时制的小时</td>
</tr>
<tr>
<td>Calendar.MINUTE</td>
<td>分钟</td>
</tr>
<tr>
<td>Calendar.SECOND</td>
<td>秒</td>
</tr>
<tr>
<td>Calendar.DAY_OF_WEEK</td>
<td>星期几</td>
</tr>
</tbody>
</table>
<h4 id="Calendar类对象信息的设置"><a href="#Calendar类对象信息的设置" class="headerlink" title="Calendar类对象信息的设置"></a>Calendar类对象信息的设置</h4><p><strong>Set设置</strong></p>
<p>如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Calendar c1 = Calendar.getInstance();</span><br></pre></td></tr></table></figure>
<p>调用：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">public final void set(int year,int month,int date)</span><br><span class="line">c1.set(2009, 6 - 1, 12);//把Calendar对象c1的年月日分别设这为：2009、6、12</span><br></pre></td></tr></table></figure>
<p>利用字段类型设置</p>
<p>如果只设定某个字段，例如日期的值，则可以使用如下set方法：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">public void set(int field,int value)</span><br></pre></td></tr></table></figure>
<p>把 c1对象代表的日期设置为10号，其它所有的数值会被重新计算</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">c1.set(Calendar.DATE,10);</span><br></pre></td></tr></table></figure>
<p>把c1对象代表的年份设置为2008年，其他的所有数值会被重新计算</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">c1.set(Calendar.YEAR,2008);</span><br></pre></td></tr></table></figure>
<p>其他字段属性set的意义以此类推</p>
<p><strong>Add设置</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Calendar c1 = Calendar.getInstance();</span><br></pre></td></tr></table></figure>
<p>把c1对象的日期加上10，也就是c1也就表示为10天后的日期，其它所有的数值会被重新计算</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">c1.add(Calendar.DATE, 10);</span><br></pre></td></tr></table></figure>
<p>把c1对象的日期减去10，也就是c1也就表示为10天前的日期，其它所有的数值会被重新计算</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">c1.add(Calendar.DATE, -10);</span><br></pre></td></tr></table></figure>
<p>其他字段属性的add的意义以此类推</p>
<h4 id="Calendar类对象信息的获得"><a href="#Calendar类对象信息的获得" class="headerlink" title="Calendar类对象信息的获得"></a>Calendar类对象信息的获得</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">Calendar c1 = Calendar.getInstance();</span><br><span class="line"><span class="comment">// 获得年份</span></span><br><span class="line"><span class="keyword">int</span> year = c1.get(Calendar.YEAR);</span><br><span class="line"><span class="comment">// 获得月份</span></span><br><span class="line"><span class="keyword">int</span> month = c1.get(Calendar.MONTH) + <span class="number">1</span>;</span><br><span class="line"><span class="comment">// 获得日期</span></span><br><span class="line"><span class="keyword">int</span> date = c1.get(Calendar.DATE);</span><br><span class="line"><span class="comment">// 获得小时</span></span><br><span class="line"><span class="keyword">int</span> hour = c1.get(Calendar.HOUR_OF_DAY);</span><br><span class="line"><span class="comment">// 获得分钟</span></span><br><span class="line"><span class="keyword">int</span> minute = c1.get(Calendar.MINUTE);</span><br><span class="line"><span class="comment">// 获得秒</span></span><br><span class="line"><span class="keyword">int</span> second = c1.get(Calendar.SECOND);</span><br><span class="line"><span class="comment">// 获得星期几（注意（这个与Date类是不同的）：1代表星期日、2代表星期1、3代表星期二，以此类推）</span></span><br><span class="line"><span class="keyword">int</span> day = c1.get(Calendar.DAY_OF_WEEK);</span><br></pre></td></tr></table></figure>
<h4 id="GregorianCalendar类"><a href="#GregorianCalendar类" class="headerlink" title="GregorianCalendar类"></a>GregorianCalendar类</h4><p>Calendar类实现了公历日历，GregorianCalendar是Calendar类的一个具体实现。</p>
<p>Calendar 的getInstance（）方法返回一个默认用当前的语言环境和时区初始化的GregorianCalendar对象。GregorianCalendar定义了两个字段：AD和BC。这是代表公历定义的两个时代。</p>
<p>下面列出GregorianCalendar对象的几个构造方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">GregorianCalendar() </span><br><span class="line">在具有默认语言环境的默认时区内使用当前时间构造一个默认的 GregorianCalendar。</span><br><span class="line"></span><br><span class="line">GregorianCalendar(<span class="keyword">int</span> year, <span class="keyword">int</span> month, <span class="keyword">int</span> date) </span><br><span class="line">在具有默认语言环境的默认时区内构造一个带有给定日期设置的 GregorianCalendar</span><br><span class="line"></span><br><span class="line">GregorianCalendar(<span class="keyword">int</span> year, <span class="keyword">int</span> month, <span class="keyword">int</span> date, <span class="keyword">int</span> hour, <span class="keyword">int</span> minute) </span><br><span class="line">为具有默认语言环境的默认时区构造一个具有给定日期和时间设置的 GregorianCalendar。</span><br><span class="line"></span><br><span class="line">GregorianCalendar(<span class="keyword">int</span> year, <span class="keyword">int</span> month, <span class="keyword">int</span> date, <span class="keyword">int</span> hour, <span class="keyword">int</span> minute, <span class="keyword">int</span> second) </span><br><span class="line">为具有默认语言环境的默认时区构造一个具有给定日期和时间设置的 GregorianCalendar。</span><br><span class="line"></span><br><span class="line">GregorianCalendar(Locale aLocale) </span><br><span class="line">在具有给定语言环境的默认时区内构造一个基于当前时间的 GregorianCalendar</span><br><span class="line"></span><br><span class="line">GregorianCalendar(TimeZone zone) </span><br><span class="line">在具有默认语言环境的给定时区内构造一个基于当前时间的 GregorianCalendar。</span><br><span class="line"></span><br><span class="line">GregorianCalendar(TimeZone zone, Locale aLocale) </span><br><span class="line">在具有给定语言环境的给定时区内构造一个基于当前时间的 GregorianCalendar。</span><br></pre></td></tr></table></figure>
<p>这里是GregorianCalendar 类提供的一些有用的方法列表：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">add</span><span class="params">(<span class="keyword">int</span> field, <span class="keyword">int</span> amount)</span> </span></span><br><span class="line"><span class="function">根据日历规则，将指定的（有符号的）时间量添加到给定的日历字段中。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">computeFields</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">转换UTC毫秒值为时间域值</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">computeTime</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">覆盖Calendar ，转换时间域值为UTC毫秒值</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">boolean</span> <span class="title">equals</span><span class="params">(Object obj)</span> </span></span><br><span class="line"><span class="function">比较此 GregorianCalendar 与指定的 Object。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">get</span><span class="params">(<span class="keyword">int</span> field)</span> </span></span><br><span class="line"><span class="function">获取指定字段的时间值</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">getActualMaximum</span><span class="params">(<span class="keyword">int</span> field)</span> </span></span><br><span class="line"><span class="function">返回当前日期，给定字段的最大值</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">getActualMinimum</span><span class="params">(<span class="keyword">int</span> field)</span> </span></span><br><span class="line"><span class="function">返回当前日期，给定字段的最小值</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">getGreatestMinimum</span><span class="params">(<span class="keyword">int</span> field)</span> </span></span><br><span class="line"><span class="function"> 返回此 GregorianCalendar 实例给定日历字段的最高的最小值。</span></span><br><span class="line"><span class="function"> </span></span><br><span class="line"><span class="function">Date <span class="title">getGregorianChange</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">获得格里高利历的更改日期。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">getLeastMaximum</span><span class="params">(<span class="keyword">int</span> field)</span> </span></span><br><span class="line"><span class="function">返回此 GregorianCalendar 实例给定日历字段的最低的最大值</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">getMaximum</span><span class="params">(<span class="keyword">int</span> field)</span> </span></span><br><span class="line"><span class="function">返回此 GregorianCalendar 实例的给定日历字段的最大值。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function">Date <span class="title">getTime</span><span class="params">()</span></span></span><br><span class="line"><span class="function">获取日历当前时间。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">long</span> <span class="title">getTimeInMillis</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">获取用长整型表示的日历的当前时间</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function">TimeZone <span class="title">getTimeZone</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">获取时区。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">getMinimum</span><span class="params">(<span class="keyword">int</span> field)</span> </span></span><br><span class="line"><span class="function">返回给定字段的最小值。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">hashCode</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">重写hashCode.</span></span><br><span class="line"><span class="function">    </span></span><br><span class="line"><span class="function"><span class="keyword">boolean</span> <span class="title">isLeapYear</span><span class="params">(<span class="keyword">int</span> year)</span></span></span><br><span class="line"><span class="function">确定给定的年份是否为闰年。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">roll</span><span class="params">(<span class="keyword">int</span> field, <span class="keyword">boolean</span> up)</span> </span></span><br><span class="line"><span class="function">在给定的时间字段上添加或减去（上/下）单个时间单元，不更改更大的字段。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">set</span><span class="params">(<span class="keyword">int</span> field, <span class="keyword">int</span> value)</span> </span></span><br><span class="line"><span class="function">用给定的值设置时间字段。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">set</span><span class="params">(<span class="keyword">int</span> year, <span class="keyword">int</span> month, <span class="keyword">int</span> date)</span> </span></span><br><span class="line"><span class="function">设置年、月、日的值。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">set</span><span class="params">(<span class="keyword">int</span> year, <span class="keyword">int</span> month, <span class="keyword">int</span> date, <span class="keyword">int</span> hour, <span class="keyword">int</span> minute)</span> </span></span><br><span class="line"><span class="function">设置年、月、日、小时、分钟的值。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">set</span><span class="params">(<span class="keyword">int</span> year, <span class="keyword">int</span> month, <span class="keyword">int</span> date, <span class="keyword">int</span> hour, <span class="keyword">int</span> minute, <span class="keyword">int</span> second)</span> </span></span><br><span class="line"><span class="function">设置年、月、日、小时、分钟、秒的值。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">setGregorianChange</span><span class="params">(Date date)</span> </span></span><br><span class="line"><span class="function">设置 GregorianCalendar 的更改日期。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">setTime</span><span class="params">(Date date)</span> </span></span><br><span class="line"><span class="function">用给定的日期设置Calendar的当前时间。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">setTimeInMillis</span><span class="params">(<span class="keyword">long</span> millis)</span> </span></span><br><span class="line"><span class="function">用给定的<span class="keyword">long</span>型毫秒数设置Calendar的当前时间。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">setTimeZone</span><span class="params">(TimeZone value)</span> </span></span><br><span class="line"><span class="function">用给定时区值设置当前时区。</span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function">String <span class="title">toString</span><span class="params">()</span> </span></span><br><span class="line"><span class="function">返回代表日历的字符串。</span></span><br></pre></td></tr></table></figure>
<h4 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.*;</span><br><span class="line">  </span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GregorianCalendarDemo</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span> </span>&#123;</span><br><span class="line">      String months[] = &#123;</span><br><span class="line">      <span class="string">"Jan"</span>, <span class="string">"Feb"</span>, <span class="string">"Mar"</span>, <span class="string">"Apr"</span>,</span><br><span class="line">      <span class="string">"May"</span>, <span class="string">"Jun"</span>, <span class="string">"Jul"</span>, <span class="string">"Aug"</span>,</span><br><span class="line">      <span class="string">"Sep"</span>, <span class="string">"Oct"</span>, <span class="string">"Nov"</span>, <span class="string">"Dec"</span>&#125;;</span><br><span class="line">      </span><br><span class="line">      <span class="keyword">int</span> year;</span><br><span class="line">      <span class="comment">// 初始化 Gregorian 日历</span></span><br><span class="line">      <span class="comment">// 使用当前时间和日期</span></span><br><span class="line">      <span class="comment">// 默认为本地时间和时区</span></span><br><span class="line">      GregorianCalendar gcalendar = <span class="keyword">new</span> GregorianCalendar();</span><br><span class="line">      <span class="comment">// 显示当前时间和日期的信息</span></span><br><span class="line">      System.out.print(<span class="string">"Date: "</span>);</span><br><span class="line">      System.out.print(months[gcalendar.get(Calendar.MONTH)]);</span><br><span class="line">      System.out.print(<span class="string">" "</span> + gcalendar.get(Calendar.DATE) + <span class="string">" "</span>);</span><br><span class="line">      System.out.println(year = gcalendar.get(Calendar.YEAR));</span><br><span class="line">      System.out.print(<span class="string">"Time: "</span>);</span><br><span class="line">      System.out.print(gcalendar.get(Calendar.HOUR) + <span class="string">":"</span>);</span><br><span class="line">      System.out.print(gcalendar.get(Calendar.MINUTE) + <span class="string">":"</span>);</span><br><span class="line">      System.out.println(gcalendar.get(Calendar.SECOND));</span><br><span class="line">      </span><br><span class="line">      <span class="comment">// 测试当前年份是否为闰年</span></span><br><span class="line">      <span class="keyword">if</span>(gcalendar.isLeapYear(year)) &#123;</span><br><span class="line">         System.out.println(<span class="string">"当前年份是闰年"</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">else</span> &#123;</span><br><span class="line">         System.out.println(<span class="string">"当前年份不是闰年"</span>);</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

    
    
    
	  <div class="full-width auto-padding tags">
      
        <a href="/tags/Java/">Java</a>
      
	  </div>
    
  </section>
</article>
    </div>
  
</section>


  <nav id="page-nav">
    
    
    <a class="next" rel="next" href="/page/2/">
      <span class="text">Next</span>
      <span class="icon icon-chevron-right"></span>
    </a>
    
  </nav>
  

      </div>
      <aside class='l_side'>
        
  <section class='m_widget links'>
<div class='header'>Links</div>
<div class='content'>
    <ul class="entry">
    
        <li><a class="flat-box" target="_blank" href="https://iiong.com/">
            <div class='name'>淮城一只猫</div>
        </a></li>
    
    </ul>
</div>
</section>

  <section class='m_widget categories'>
<div class='header'>Categories</div>
<div class='content'>
    
    <ul class="entry">
    
        <li><a class="flat-box" href="/categories/Android基础/"><div class='name'>Android基础</div><div class='badget'>1</div></a></li>
    
    </ul>
    
</div>
</section>

  
<div class="m_widget tagcloud">
    <div class="header">Tags</div>
    <div class='content'>
        <a href="/tags/Android/" style="font-size: 14px; color: #808080">Android</a> <a href="/tags/HTML/" style="font-size: 14px; color: #808080">HTML</a> <a href="/tags/Java/" style="font-size: 20px; color: #000">Java</a> <a href="/tags/Python/" style="font-size: 14px; color: #808080">Python</a>
    </div>
</div>



      </aside>
      <script>setLoadingBarProgress(60);</script>
    </div>
  </div>
  <footer id="footer" class="clearfix">

	<div class="social-wrapper">
  	
      
        <a href="https://github.com/stkevintan" class="social github"
          target="_blank" rel="external">
          <span class="icon icon-github"></span>
        </a>
      
        <a href="https://twitter.com/kevinsfork" class="social twitter"
          target="_blank" rel="external">
          <span class="icon icon-twitter"></span>
        </a>
      
        <a href="/atom.xml" class="social rss"
          target="_blank" rel="external">
          <span class="icon icon-rss"></span>
        </a>
      
    
  </div>
  
  <div>Theme <a href='https://github.com/stkevintan/hexo-theme-material-flow' class="codename">MaterialFlow</a> designed by <a href="http://keyin.me/" target="_blank">Kevin Tan</a>.</div>
  
</footer>


  <script>setLoadingBarProgress(80);</script>
  

<script src="//apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src='//cdn.bootcss.com/node-waves/0.7.5/waves.min.js'></script>
<script src="//cdn.bootcss.com/scrollReveal.js/3.3.2/scrollreveal.min.js"></script>
<script src="/js/jquery.fitvids.js"></script>
<script>
	var GOOGLE_CUSTOM_SEARCH_API_KEY = "";
	var GOOGLE_CUSTOM_SEARCH_ENGINE_ID = "";
	var ALGOLIA_API_KEY = "";
	var ALGOLIA_APP_ID = "";
	var ALGOLIA_INDEX_NAME = "";
  var AZURE_SERVICE_NAME = "";
  var AZURE_INDEX_NAME = "";
  var AZURE_QUERY_KEY = "";
  var BAIDU_API_ID = "";
  var SEARCH_SERVICE = "hexo";
  var ROOT = "/"||"/";
  if(!ROOT.endsWith('/'))ROOT += '/';
</script>
<script src="/js/search.js"></script>
<script src="/js/app.js"></script>


  <script>setLoadingBarProgress(100);</script>
</body>
</html>
